
package com.myopen.model;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.kit.UUIDKit;

public class Config extends Model<Config>{

	private static final long serialVersionUID = -3869616476783672270L;
	public static final Config dao=new Config();
	
	public Page<Record> pagequery(Record record){
		return null;
    }
	
	private void saveOrUpdate(String name,String value){
		Config bo=Config.dao.findFirst("select * from t_config t where t.name=? ",name);
		if(bo==null){
			bo=new Config();
			bo.set("id", UUIDKit.getUUID());
			bo.set("removed", "0");
			bo.set("createTime", new Date());
			bo.set("updateTime", new Date());
			bo.set("name", name);
			bo.set("value", value);
			bo.save();
		}else{
			bo.set("updateTime", new Date());
			bo.set("value", value);
			bo.update();
		}
	}

	public void saveString(String name,String value){
		saveOrUpdate(name,value);
    }

	public void saveMap(String name,Map<String,Object> obj){
		String value=JsonKit.toJson(obj);
		saveOrUpdate(name,value);
	}
	
	public String getValueToString(String name){
		String sql="select * from t_config t where t.name=? ";
		Record r=Db.findFirst(sql,name);
		if(r!=null){
			String value=r.getStr("value");
			return value;
		}
		return null;
	}

	public Map<String,Object> getValueToMap(String name){
		String value=getValueToString(name);
		if(!StrKit.isBlank(value)){
			return (Map<String,Object>)JSON.parse(value);
		}
		return new HashMap<>();
	}

}
